#!/bin/bash

installApps()
{
    clear
    OS="$REPLY" ## <-- This $REPLY is about OS Selection
    echo "自动安装docker,docker-compose中."
    echo ""
    echo ""
    
    ISACT=$( (sudo systemctl is-active docker ) 2>&1 )
    ISCOMP=$( (docker-compose -v ) 2>&1 )

    if [[ "$ISACT" != "active" ]]; then
        read -rp "Docker-CE (y/n): " DOCK
    else
        echo "Docker appears to be installed and running."
        echo ""
        echo ""
    fi

    if [[ "$ISCOMP" == *"command not found"* ]]; then
        read -rp "Docker-Compose (y/n): " DCOMP
    else
        echo "Docker-compose appears to be installed."
        echo ""
        echo ""
    fi
    
    startInstall
}

startInstall() 
{
    clear
    echo "#######################################################"
    echo "###                  准备安装中...                    ###"
    echo "#######################################################"
    echo ""
    sleep 3s

    #######################################################
    ###           Install for Debian / Ubuntu           ###
    #######################################################

    if [[ "$OS" != "1" ]]; then
        echo "    1. Installing System Updates... this may take a while...be patient. If it is being done on a Digial Ocean VPS, you should run updates before running this script."
        (sudo apt update && sudo apt upgrade -y) > ~/docker-script-install.log 2>&1 &
        ## Show a spinner for activity progress
        pid=$! # Process Id of the previous running command
        spin='-\|/'
        i=0
        while kill -0 $pid 2>/dev/null
        do
            i=$(( (i+1) %4 ))
            printf "\r${spin:$i:1}"
            sleep .1
        done
        printf "\r"

        echo "    2. Install Prerequisite Packages..."
        sleep 2s

        sudo apt install curl wget git -y >> ~/docker-script-install.log 2>&1

        echo "    3. Installing Docker-CE (Community Edition)..."
        sleep 2s

        curl -fsSL https://get.docker.com | sh >> ~/docker-script-install.log 2>&1

        echo "      - docker-ce version is now:"
        DOCKERV=$(docker -v)
        echo "          "${DOCKERV}
        sleep 3s
        #切换docker源
        switch_docker_mirror

        if [[ "$OS" == 2 ]]; then
            echo "    5. Starting Docker Service"
            sudo systemctl docker start >> ~/docker-script-install.log 2>&1
        fi

    fi
        
    
    #######################################################
    ###              Install for CentOS 7 or 8          ###
    #######################################################
    if [[ "$OS" == "1" ]]; then
        if [[ "$DOCK" == [yY] ]]; then
            echo "    1. Updating System Packages..."
            sudo yum check-update >> ~/docker-script-install.log 2>&1

            echo "    2. Installing Prerequisite Packages..."
            sudo yum install git curl wget -y >> ~/docker-script-install.log 2>&1

            echo "    3. Installing Docker-CE (Community Edition)..."

            sleep 2s
            (curl -fsSL https://get.docker.com/ | sh) >> ~/docker-script-install.log 2>&1

            echo "    4. Starting the Docker Service..."

            sleep 2s


            sudo systemctl start docker >> ~/docker-script-install.log 2>&1

            echo "    5. Enabling the Docker Service..."
            sleep 2s

            sudo systemctl enable docker >> ~/docker-script-install.log 2>&1

            echo "      - docker version is now:"
            DOCKERV=$(docker -v)
            echo "        "${DOCKERV}
            sleep 3s
            #切换docker源
            switch_docker_mirror
        fi
    fi

    #######################################################
    ###               Install for Arch Linux            ###
    #######################################################

    if [[ "$OS" == "5" ]]; then
        read -rp "Do you want to install system updates prior to installing Docker-CE? (y/n): " UPDARCH
        if [[ "UPDARCH" == [yY] ]]; then
            echo "    1. Installing System Updates... this may take a while...be patient."
            (sudo pacman -Syu) > ~/docker-script-install.log 2>&1 &
            ## Show a spinner for activity progress
            pid=$! # Process Id of the previous running command
            spin='-\|/'
            i=0
            while kill -0 $pid 2>/dev/null
            do
                i=$(( (i+1) %4 ))
                printf "\r${spin:$i:1}"
                sleep .1
            done
            printf "\r"
        else
            echo "    1. Skipping system update..."
            sleep 2s
        fi

        echo "    2. Installing Prerequisit Packages..."
        sudo pacman -Sy git curl wget >> ~/docker-script-install.log 2>&1

        echo "    3. Installing Docker-CE (Community Edition)..."
            sleep 2s

            curl -fsSL https://get.docker.com | sh >> ~/docker-script-install.log 2>&1

            echo "    - docker-ce version is now:"
            DOCKERV=$(docker -v)
            echo "        "${DOCKERV}
            sleep 3s
            #切换docker源
            switch_docker_mirror
    fi

    #######################################################
    ###              Install for OpenEule          ###
    #######################################################
    if [[ "$OS" == "6" ]]; then
        if [[ "$DOCK" == [yY] ]]; then
            echo "    1. 下载docker..."
            sudo yum install git curl wget -y 

            sleep 1s

            wget https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/static/stable/x86_64/docker-20.10.17.tgz

            echo "    2. 开始解压..."
            tar -xzvf docker-20.10.17.tgz

            cp docker/ /usr/bin/*
            echo "    3. 注册docker服务..."
            sudo tee /etc/docker/daemon.json <<-'EOF'
            [Unit]
            Description=Docker Application Container Engine
            Documentation=https://docs.docker.com
            After=network-online.target firewalld.service
            Wants=network-online.target
            
            [Service]
            Type=notify
            ExecStart=/usr/bin/dockerd 
            ExecReload=/bin/kill -s HUP $MAINPID
            LimitNOFILE=infinity
            LimitNPROC=infinity
            LimitCORE=infinity
            TimeoutStartSec=0
            Delegate=yes
            KillMode=process
            Restart=on-failure
            StartLimitBurst=3
            StartLimitInterval=60s
            
            [Install]
            WantedBy=multi-user.target

EOF

            sudo chmod a+x /etc/systemd/system/docker.service
            echo "    4. 安装完成..."
            sleep 1s

            systemctl start docker
            systemctl enable docker
            #切换docker源
            switch_docker_mirror
        fi
    fi

    if [[ "$DOCK" == [yY] ]]; then
        # add current user to docker group so sudo isn't needed
        echo ""
        echo "  - Attempting to add the currently logged in user to the docker group..."

        sleep 2s
        sudo usermod -aG docker "${USER}" >> ~/docker-script-install.log 2>&1
        echo "  - You'll need to log out and back in to finalize the addition of your user to the docker group."
        echo ""
        echo ""
        sleep 3s
    fi

    if [[ "$DCOMP" = [yY] ]]; then
        echo "############################################"
        echo "######     Install Docker-Compose     ######"
        echo "############################################"

        # install docker-compose
        echo ""
        echo "    1. Installing Docker-Compose..."
        echo ""
        echo ""
        sleep 2s

        ######################################
        ###     Install Debian / Ubuntu    ###
        ######################################        
        
        if [[ "$OS" == "2" || "$OS" == "3" || "$OS" == "4" ]]; then
            sudo apt install docker-compose -y >> ~/docker-script-install.log 2>&1
        fi

        ######################################
        ###        Install CentOS 7 or 8   ###
        ######################################

        if [[ "$OS" == "1" ]]; then
            curl -L https://get.daocloud.io/docker/compose/releases/download/v2.9.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
            
            chmod +x /usr/local/bin/docker-compose
        fi

        ######################################
        ###        Install Arch Linux      ###
        ######################################

        if [[ "$OS" == "5" ]]; then
            sudo pacman -Sy >> ~/docker-script-install.log 2>&1
            sudo pacman -Sy docker-compose > ~/docker-script-install.log 2>&1
        fi

        ######################################
        ###        Install OpenEule        ###
        ######################################

        if [[ "$OS" == "6" ]]; then
            curl -L https://get.daocloud.io/docker/compose/releases/download/v2.9.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose

            chmod +x /usr/local/bin/docker-compose
        fi



        echo ""

        echo "      - Docker Compose Version is now: " 
        DOCKCOMPV=$(docker-compose --version)
        echo "        "${DOCKCOMPV}
        echo ""
        echo ""
        sleep 3s
    fi

    ##########################################
    #### Test if Docker Service is Running ###
    ##########################################
    ISACT=$( (sudo systemctl is-active docker ) 2>&1 )
    if [[ "$ISACt" != "active" ]]; then
        echo "Giving the Docker service time to start..."
        while [[ "$ISACT" != "active" ]] && [[ $X -le 10 ]]; do
            sudo systemctl start docker >> ~/docker-script-install.log 2>&1
            sleep 10s &
            pid=$! # Process Id of the previous running command
            spin='-\|/'
            i=0
            while kill -0 $pid 2>/dev/null
            do
                i=$(( (i+1) %4 ))
                printf "\r${spin:$i:1}"
                sleep .1
            done
            printf "\r"
            ISACT=`sudo systemctl is-active docker`
            let X=X+1
            echo "$X"
        done
    fi
    sleep 1s
    echo '拉取git文件'
    clone_soms_code
    
    exit 1
}

clone_soms_code(){
  cd /
  if [ ! -d Fyc_Jumpserver  ];then
    mkdir Fyc_Jumpserver
    cd Fyc_Jumpserver
    echo '克隆代码....'
    git clone https://gitee.com/H0nGzA1/fyc_soms.git
    cd fyc_soms

    add_permission

    echo '启动soms...'
    # docker-compose -f ./fycjumpserver-docker-compose.yaml  -f ./zabbix-docker-compose.yaml up -d
    ./start.sh
  else
    rm -rf Fyc_Jumpserver
    mkdir Fyc_Jumpserver
    cd Fyc_Jumpserver
    echo '克隆代码....'
    git clone https://gitee.com/H0nGzA1/fyc_soms.git
    cd fyc_soms
    
    add_permission

    echo '启动soms...'
    # docker-compose -f ./fycjumpserver-docker-compose.yaml  -f ./zabbix-docker-compose.yaml up -d
    ./start.sh
  fi
}

add_permission(){
echo "赋予所有目录执行权限."
chmod -R 777 *
}

switch_docker_mirror(){
echo "切换docker国内镜像源..."
# 1.创建一个目录
sudo mkdir -p /etc/docker

    # 2.编写配置文件
sudo tee /etc/docker/daemon.json <<-'EOF'
{
"registry-mirrors":[
    "https://registry.docker-cn.com",
    "http://hub-mirror.c.163.com",
    "https://docker.mirrors.ustc.edu.cn",
    "https://cr.console.aliyun.com",
    "https://mirror.ccs.tencentyun.com"
]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker
}

echo ""
echo ""

clear

PS3="请输入数字匹配你当前运行的系统OS / 发行版: "
select _ in \
    "CentOS 7 and 8" \
    "Debian 10/11 (Buster / Bullseye)" \
    "Ubuntu 18.04 (Bionic)" \
    "Ubuntu 20.04 / 21.04 / 22.04 (Focal / Hirsute / Jammy)" \
    "Arch Linux" \
    "OpenEule" \
    "End this Installer"
do
  case $REPLY in
    1) installApps ;;
    2) installApps ;;
    3) installApps ;;
    4) installApps ;;
    5) installApps ;;
    6) installApps ;;
    7) exit ;;
    *) echo "错误选项请重试." ;;
  esac
done



main(){
  installApps
}
main